package com.shengqiang.cloud.oauth2.repository;

import com.shengqiang.cloud.oauth2.model.Client;
import com.shengqiang.cloud.oauth2.utils.RedisTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by Administrator on 2017/12/9.
 * 认证消息查询
 */
@Repository
public class OAuthClientDao {

    private static final Logger logger= LoggerFactory.getLogger(OAuthClientDao.class);

    private String hashClientKey="h:oauth2:client";

    @Autowired
    private RedisTool<Client> redisTool;

    /**
     * 插入,更新客户端信息
     * @param client
     * @return
     */
    public boolean saveClient(Client client){
        boolean flag=false;
        String clientKey= redisTool.generatorClientKey(client.getClientId());
        try{
            Client hasClient=queryClient(client.getClientId());
            redisTool.saveOpsHash(hashClientKey,clientKey,client);
            flag=true;
        }catch (Exception ex){
            logger.error("注册客户的信息失败:{}",ex.getMessage(),ex);
        }
        return flag;
    }

    /**
     * 根据客户端ID,查询客户端信息
     * @param clientId
     * @return
     */
    public Client queryClient(String clientId){
        try{
            String hashValueKey=redisTool.generatorClientKey(clientId);
            return redisTool.queryOpsHash(hashClientKey,hashValueKey,Client.class);
        }catch (Exception ex){
            logger.error("查询指定Id的客户端出现异常:{}",ex.getMessage(),ex);
        }

        return null;
    }

    /**
     * 查询所有已注册的客户端信息
     * @return
     */
    public List<Client> queryClients(){
       try{
           List<Client> clients=redisTool.queryOpsHashList(hashClientKey,Client.class);
           return clients;
       }catch (Exception ex){
           logger.error("查询客户端注册类别出现异常:{}",ex.getMessage(),ex);
       }
        return null;
    }

    public boolean deleteClient(String clientId){
        try{
            String valueKey=redisTool.generatorClientKey(clientId);
            return redisTool.deleteOpsHash(hashClientKey,valueKey);
        }catch (Exception ex){
            logger.error("删除客户端信息出现异常:{}",ex.getMessage(),ex);
        }

        return false;
    }
}
